import express from "express";
import Result from "../../common/result.js";
import fse from "fs-extra";
import { OUTPUT_PATH } from "../../const/index.js";
import path from "node:path";
import { zipDirectory } from "../../utils/file.js";

const downloadRouter = express.Router();

downloadRouter.post("/", async (req, res) => {
  try {
    const { fileHash, fileType } = req.body;
    const filePath =
      fileType === "folder"
        ? path.join(OUTPUT_PATH, fileHash)
        : path.join(OUTPUT_PATH, fileHash + "." + fileType);
    res.on("close", () => {
      //下载完成后删除对应的文件
      fse.remove(filePath);
    });
    if (fileType === "folder") {
      const archive = zipDirectory(filePath);
      archive.finalize();
      res.status(200);
      return archive.pipe(res);
    }
    return res.download(filePath);
  } catch (error) {
    res.status(500);
    return res.send(Result.error(error, "参数错误", 500));
  }
});

export default downloadRouter;
